const pageHelper = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('project_helpers_config.js').(_, __, helper) => helper.replace('.js', '');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { teamStore } = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/team_store.js');
const { projectContext } = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('helpers/project_context.js');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    projectId: '',
    filterOptions: [
      { text: '全部', value: 'all' },
      { text: '负责人', value: 'leader' },
      { text: '项目经理', value: 'manager' },
      { text: '团队成员', value: 'member' }
    ],
    selectedFilter: 'all',
    searchValue: '',
    sortMenus: [
      { label: '按角色', value: 'role' },
      { label: '按部门', value: 'department' },
      { label: '按加入时间', value: 'joinTime' }
    ],
    sortType: 'role',
    isAdmin: false // 当前用户是否管理员权限
  },
  
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_team_list' });
    
    // 创建MobX绑定
    this.storeBindings = createStoreBindings(this, {
      store: teamStore,
      fields: ['loading', 'error', 'teamMembers', 'pagination'],
      actions: ['getProjectTeam', 'setFilters']
    });
    
    if (options.id) {
      this.setData({ projectId: options.id });
      this.getProjectTeam(options.id);
    } else {
      // 尝试从上下文获取当前项目
      const currentProjectId = projectContext.getCurrentProjectId();
      if (currentProjectId) {
        this.setData({ projectId: currentProjectId });
        this.getProjectTeam(currentProjectId);
      } else {
        pageHelper.showErrorToast('未找到项目信息');
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    }
    
    // 检查当前用户权限
    this._checkAdminPermission();
  },
  
  // 切换角色过滤器
  onRoleFilterChange: function(e) {
    const role = e.currentTarget.dataset.value;
    this.setData({ selectedFilter: role });
    
    // 设置过滤条件并刷新列表
    this.setFilters({ role });
    this.getProjectTeam(this.data.projectId);
  },
  
  // 搜索团队成员
  onSearch: function(e) {
    const search = e.detail;
    this.setData({ searchValue: search });
    
    // 设置搜索条件并刷新列表
    this.setFilters({ search });
    this.getProjectTeam(this.data.projectId);
  },
  
  // 切换排序方式
  onSortChange: function(e) {
    const sortType = e.currentTarget.dataset.value;
    this.setData({ sortType });
    
    // 设置排序条件并刷新列表
    this.setFilters({ sortType });
    this.getProjectTeam(this.data.projectId);
  },
  
  // 添加团队成员
  onAddMember: function() {
    wx.navigateTo({
      url: `../edit/team_edit?projectId=${this.data.projectId}`
    });
  },
  
  // 查看成员详情
  onMemberTap: function(e) {
    const memberId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/team_detail?id=${memberId}&projectId=${this.data.projectId}`
    });
  },
  
  // 编辑团队成员
  onEditMember: function(e) {
    const memberId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../edit/team_edit?id=${memberId}&projectId=${this.data.projectId}`
    });
  },
  
  // 管理成员权限
  onManagePermission: function(e) {
    const memberId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../permission/team_permission?id=${memberId}&projectId=${this.data.projectId}`
    });
  },
  
  // 分配工作量
  onAssignWorkload: function() {
    wx.navigateTo({
      url: `../workload/team_workload?projectId=${this.data.projectId}`
    });
  },
  
  // 检查当前用户是否有管理员权限
  _checkAdminPermission: function() {
    // 从全局用户权限检查（实际实现可能不同）
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    const userPermissions = userInfo.permissions || {};
    
    // 检查是否有项目团队管理权限
    const isAdmin = userPermissions.project?.admin === true || 
                    userPermissions.member?.write === true;
    
    this.setData({ isAdmin });
  },
  
  onPullDownRefresh: function() {
    // 下拉刷新
    this.getProjectTeam(this.data.projectId).then(() => {
      wx.stopPullDownRefresh();
    }).catch(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  onReachBottom: function() {
    // 上拉加载更多（如果有分页）
    if (this.data.pagination.page * this.data.pagination.size < this.data.pagination.total) {
      const nextPage = this.data.pagination.page + 1;
      this.getProjectTeam(this.data.projectId, { page: nextPage, append: true });
    }
  },
  
  onUnload: function() {
    // 销毁MobX绑定
    this.storeBindings.destroyStoreBindings();
  }
}); 